import React, { useCallback, useEffect, useState } from 'react';

import searchIcon from '../../static/svgs/search.svg';
import searchDown from '../../static/svgs/downarrow.svg';
import searchUp from '../../static/svgs/uparrow.svg';
import searchClose from '../../static/svgs/close-x.svg';
import IDEOutputs from './outputs';
import IDEEvents from './events';
import IDEWorldState from './worldstate';
import { Input } from 'tea-component';
import useAppStore from '@ide/store';
import { useIdeStore } from 'ide-plugin';

export default function BottomConsole() {
  const [tabs] = useState<{ id: string; label: string }[]>([
    { id: 'output', label: '输出' },
    { id: 'event', label: '事件' },
    { id: 'worldstate', label: '世界状态' }
  ]);

  const { clearOutputText, setOutputText, originOutputText, outputText, clearOriginOutputText } = useAppStore();
  // const [bottomCurrentTab, setCurrentTab] = useState<'output' | 'event' | 'worldstate'>('output')
  const { bottomCurrentTab, setBottomCurrentTab, clearEventData, setWorldState } = useAppStore();
  const { setIsHideBottomContent } = useIdeStore();
  const [searchContent, setSearchContent] = useState('');
  const [currentMatchIndex, setCurrentMatchIndex] = useState(0);

  // 清除日志
  // const clearLog = () => {
  //   clearOutputText()
  // }
  // 清空input框
  const clearInputLog = () => {
    setSearchContent('');
    clearOutputText();
    outputText.map((item: string) => {
      item = item.replace(/match_current/ig, '').replace(/match/ig, '');
      setOutputText(item);
      return item;
    });
  };
  useEffect(() => {
    clearOutputText();
    originOutputText.map(item => {
      const contents = markupTags(item).split('|||');
      const searchText = encodeHTML(searchContent);
      const regexp = new RegExp(searchText, 'gi');
      const newContents = contents.map(function (text) {
        if (text.startsWith('<') && text.endsWith('>')) {
          return text;
        }
        const matchText = text.replace(regexp, '<span class="match">$&</span>');
        return matchText;
      });
      setOutputText(newContents.join(''));
      return newContents.join('');
    });
  }, [searchContent, originOutputText]);

  const encodeHTML = function (str: string) {
    if (typeof str === 'string') {
      return str.replace(/<|&|>/g, function (matches) {
        return ({
          '<': '&lt;',
          '>': '&gt;',
          '&': '&amp;'
        })[matches] as string;
      });
    }
    return '';
  };
  const markupTags = function (str: string) {
    if (typeof str === 'string') {
      return str.replace(/<|>/g, function (matches) {
        return ({
          '<': '|||<',
          '>': '>|||'
        })[matches] as string;
      });
    }
    return '';
  };

  // 下移
  const downHandle = () => {
    clearOutputText();
    const indexArray: Array<number> = [];
    const matchArray = outputText.filter((item, idx) => {
      if (item.includes('match')) {
        indexArray.push(idx);
      }
      return item.includes('match');
    });
    const matchLength = matchArray.length;
    if (matchLength) {
      const index = currentMatchIndex >= matchLength - 1 ? 0 : currentMatchIndex + 1;
      setCurrentMatchIndex(index);
      outputText.map((item: string, idx: number) => {
        item = item.replace(/match_current/ig, '');
        if (idx === indexArray[index]) {
          item = item.replace(/match/ig, ' match  match_current');
        }
        setOutputText(item);
        return item;
      });
    }
  };

  // 上移
  const upHandle = () => {
    clearOutputText();
    const indexArray: Array<number> = [];
    const matchArray = outputText.filter((item, idx) => {
      if (item.includes('match')) {
        indexArray.push(idx);
      }
      return item.includes('match');
    });
    const matchLength = matchArray.length;
    if (matchLength) {
      const index = currentMatchIndex <= 0 ? matchLength - 1 : currentMatchIndex - 1;
      setCurrentMatchIndex(index);
      outputText.map((item: string, idx: number) => {
        item = item.replace(/match_current/ig, '');
        if (idx === indexArray[index]) {
          item = item.replace(/match/ig, ' match  match_current');
        }
        setOutputText(item);
        return item;
      });
    }
  };

  const clearConsole = useCallback(() => {
    if (bottomCurrentTab) {
      switch (bottomCurrentTab) {
        case 'output':
          clearOriginOutputText();
          clearOutputText();
          break;
        case 'event':
          clearEventData();
          break;
        case 'worldstate':
          setWorldState([]);
          break;
        default:
          break;
      }
    }
  }, [bottomCurrentTab]);

  return (
    <>
      <div className="tabs">
        {
          tabs.map((tab) => (
            <div key={tab.id} className={tab.id === bottomCurrentTab ? 'current' : ''} onClick={() => setBottomCurrentTab(tab.id)}>
              <span title={tab.label}>{tab.label}</span>
            </div>
          ))
        }
        <span className="fn-right tabs-search-wrapper">
          {
            bottomCurrentTab === 'output' && (
              <span className="search-tools">
                <img className="tabs-search-pre" src={searchIcon} />
                <Input className="tabs-search" value={searchContent} onChange={(val: string) => setSearchContent(val)} placeholder="搜索"></Input>
                <span className="tabs-search-icon">
                  <img className="tabs-search-down" src={searchDown} onClick={downHandle} />
                  <img className="tabs-search-up" src={searchUp} onClick={upHandle} />
                  <img className="tabs-search-close" src={searchClose} onClick={clearInputLog} />
                </span>
              </span>
            )
          }
          <span className="clear-all" title="清除" onClick={clearConsole}>清除</span>
          <span className="down-icon ico-min" onClick={() => setIsHideBottomContent(true)}></span>
        </span>
      </div>

      <div className="tabs-panel">
        <IDEOutputs style={{ display: bottomCurrentTab === 'output' ? 'block' : 'none' }} />
        <IDEEvents style={{ display: bottomCurrentTab === 'event' ? 'block' : 'none' }} />
        <IDEWorldState style={{ display: bottomCurrentTab === 'worldstate' ? 'block' : 'none' }} />
        {/* {bottomCurrentTab === 'output' && <IDEOutputs></IDEOutputs>}
        {bottomCurrentTab === 'event' && <IDEEvents></IDEEvents>}
        {bottomCurrentTab === 'worldstate' && <IDEWorldState></IDEWorldState>} */}
      </div>
    </>
  );
}
